<?php
/*
 * @Author: your name
 * @Date: 2021-12-07 09:50:02
 * @LastEditTime: 2022-01-17 10:22:39
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \property\app\Http\Controllers\find_shop\User.php
 */

namespace App\Http\Controllers\daily_partTime;

use  Illuminate\Support\Facades\Request;
use  App\Http\Controllers\redis\RedisController as Redis;
use  App\Models\daily_partTime\DailyParttimeOnMessage;
use Exception;

class CustomerService extends BaseController
{


    // 客户发送给客服
    public function sendToService()
    {
        if (Request::has('message')) {
            $message =  Request::input('message');
            $userLoginMsg = $this->getLoginAllMsg();
            $openid = $userLoginMsg['openid'];
            $date = date('Y-m-d H:i:s');
            $message_id =   $this->sendMessageMysql($message, $openid  , 1 , $date);
            $getAll        = Redis::redishGetAll($this->service_redis, ['RedisDB' => $this->dbNumber]);   //所有客服 fd
            foreach ($getAll as $key => $val) {
                $bindOpenid =  Redis::hGET($this->online_key, $key, ['RedisDB' => $this->dbNumber]);  //找到该fd是否是他的opneid
                if ($bindOpenid &&  $bindOpenid == $val) {
                    try {                                                                                              //发送给的客服
                        $_POST['WEBSOCKET_SERVER']->push($key, json_encode(['type' => 'message', 'source' => $message,'toCharacter'=>'service' ,'customer_openid'=>$openid,'avatarUrl'=>$userLoginMsg['avatarUrl'],'nickName'=>$userLoginMsg['nickName'],'user_id'=> $userLoginMsg['id'],'message_id' => $message_id,'date'=> $date]));
                    } catch (Exception $e) {
                        //todo;
                    }
                } else {
                    Redis::hDel($this->service_redis, $key, ['RedisDB' => $this->dbNumber]);   //删除客服fd
                }
            }

            // $_POST['WEBSOCKET_SERVER']->push(Request::input('fd'), json_encode(['type' => 'message', 'source' => $message]));



            return $this->create(200, '发送成功');
        }
    }
    // 客服发送给客户
    public function sendToCustomer()
    {
        if (Request::has('message') && Request::has('openid')) {
            $message =  Request::input('message');
            $openid = Request::input('openid');
            $date = date('Y-m-d H:i:s');

            $message_id =  $this->sendMessageMysql($message, $openid, 0, $date);

            $fdbind_key  = $this->customRedisKey . $openid;
            $allFd   = Redis::smembers($fdbind_key, ['RedisDB' => $this->dbNumber]);    //这个账号所有fd
            if ($allFd) {
                foreach ($allFd as  $val) {           //循环所有fd 
                    $bindOpenid =  Redis::hGET($this->online_key, $val, ['RedisDB' => $this->dbNumber]);  //找到该fd是否是他的opneid 
                    //找到该fd是否是他的opneid
                    if ($bindOpenid && $bindOpenid == $openid) {           //当前绑定openid是否为 
                        try {                                                                         //发送给客户
                            $_POST['WEBSOCKET_SERVER']->push($val, json_encode(['type' => 'message', 'toCharacter'=>'customer','source' => $message, 'message_id' => $message_id,'date'=> $date]));
                        } catch (Exception $e) {
                            //todo;
                        }
                    } else {
                        Redis::spop($fdbind_key, $val, ['RedisDB' => $this->dbNumber]);
                    }
                }
            }
            return $this->create(200, '发送成功');
        }
    }



    public function sendMessageMysql($message, $openid, $is_customer, $date)
    {
        $formData['customer_openid'] = $openid; //客户openid
        $formData['message'] =  $message;
        $formData['send_time'] = $date;
        $formData['is_customer'] = $is_customer;
        $id = DailyParttimeOnMessage::add($formData);
        return $id;
    }

    public function messageHistory($openid = null)
    {
        $whereStr = '';
        $keyWord = array_filter(Request::input('keyWord'), 'filtrfunction');
        if (!empty($keyWord)) {
            $whereStr .= havaWhereLikeJoinEqual($keyWord);
        }
        $limitrStr = Request::has('limit') && Request::has('page') ? limit_joint(Request::input('page'), Request::input('limit')) : '';
        $list =  DailyParttimeOnMessage::historyList($openid ? $openid :$this->getLoginMsg(), $whereStr, $limitrStr);
        return $this->create(200, '查询成功', $list);
    }

    public function messageServiceHistory(){
        if(Request::has('openid')){
            return $this->messageHistory(Request::input('openid'));
        }
    }


    //未读消息多少条
    public function messageNotReadNumber()
    {
        $is_customer =   $this->getLoginAllMsg()['is_customer'];
        if($is_customer == 1){
            $res =  DailyParttimeOnMessage::messageNotRead($this->getLoginMsg());
        }else if($is_customer == 0){
            $res =  DailyParttimeOnMessage::messageServiceNotRead();
        }
        return $this->create(200, '查询成功',$res[0]['count']);

    }


    //阅读未读消息
    public function messageCustomerRead( $openid,$is_customer = 0)
    {
        $res = DailyParttimeOnMessage::messageCustomerRead( $openid? $openid:$this->getLoginMsg(),$is_customer);  //阅读客服发送的内容
        return $this->create(200, '修改成功');
    }

    //阅读单条消息
    public function messageReadOne()
    {
        if (Request::has('message_id')) {
            $res = DailyParttimeOnMessage::messageReadOne( Request::input('message_id'));
            return $this->create(200, '修改成功');
        }
    }

   //客服未读消息列表
    public function messageServiceNotReadList(){
        $limitrStr = Request::has('limit') && Request::has('page') ? limit_joint(Request::input('page'), Request::input('limit')) : '';
        $whereStr = '';
        $keyWord = array_filter(Request::input('keyWord'), 'filtrfunction');
        if (!empty($keyWord)) {
            $whereStr .= havaWhereLikeJoinEqual($keyWord);
        }
        $list =  DailyParttimeOnMessage::messageServiceNotReadList( $whereStr ,  $limitrStr);    
        return $this->create(200, '查询成功',$list);
    }


    public function messageServiceRead(){
        if(Request::has('openid')){
            return $this->messageCustomerRead(Request::input('openid'),1); 
        }
    }
}
